﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;

namespace Teambuy.Filters
{
    /// <summary>
    /// 检测用户是否绑定了用户信息
    /// </summary>
    public class CheckUserAttribute : Attribute, IAsyncActionFilter
    {

        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var db = App.GetService<ISqlSugarClient>();

            int userId = App.User?.FindFirstValue("UserId").ObjToInt() ?? 0;

            if (userId == 0)
            {
                context.Result = new JsonResult(new { code = 401 });

                return;
            }

            var user = await db.Queryable<Entity.Client>().FirstAsync(x => x.Id == userId);

            if (user == null || !user.BindPhone)
            {
                context.Result = new JsonResult(new { code = 4009, msg = "请先绑定手机号" });

                return;
            }

            await next();
        }
    }
}
